<?php
function validarRol() {
	global $rol;
	$flags = array();
	$rol->set('roles','fecha',time());
	if (isset($_POST['descripcion'])) $rol->set('roles','descripcion',htmlentities($_POST['descripcion']));
	if (isset($_POST['nombre']) && (!empty($_POST['nombre']))) $rol->set('roles','nombre',htmlentities($_POST['nombre'])); else $flags = push_validate($flags,'nombre','Debe escribir un nombre para el rol.');

	$students_actions = array('todo','no-regulares','potenciales','sin-confirmar','disponibles','delete','update','read','create');
	$groups_actions = array('plan','accountancy','read-message','send-message','create-workshop','read-workshop','calendar','todo','inactivos','delete','update-students','update','read','create');

	$_students = array('students',$students_actions);
	$_groups = array('groups',$groups_actions);

	$arr_modules = array($_students,$_groups);

	$str_permission = "";

	foreach ($arr_modules as $module) {
		$hex = convertArrayToHex($module,4);
		$str_permission .= $hex."-";
	}
	$str_permission = substr($str_permission, 0, strlen($str_permission)-1);
	$rol->set('roles','permisos',$str_permission);
	
	return $flags;
}

function convertArrayToHex($_module,$digitos) {
	$mod = $_module[0];
	$mod_activated = $mod.'-default';
	$arr_bin = array();

	if (isset($_POST[$mod_activated])) {
		foreach ($_module[1] as $action) {
			$current_action = $mod.'-'.$action;
			if (array_key_exists($current_action,$_POST)) array_push($arr_bin, 1); else array_push($arr_bin, 0);
		}
		array_push($arr_bin, 1);
	}
	$bin = convertArrayToBin($arr_bin,$digitos);
	return convertBinToHex($bin,$digitos);
}

function convertArrayToBin($arr,$digitos) {
	$str = implode("",$arr);
	for ($i = strlen($str);$i<($digitos*4);$i++) $str = '0'.$str;
	return $str;
}
function convertBinToHex($bin,$digitos) {
	$hex = dechex(bindec($bin));
	for ($i = strlen($hex);$i<$digitos;$i++) $hex = '0'.$hex;
	return $hex;
}
function convertHexToBin($hex,$digitos) {
	$bin = decbin(hexdec($hex));
	for ($i = strlen($bin);$i<($digitos*4);$i++) $bin = '0'.$bin;
	return $bin;
}
function push_validate($array,$item,$message) {
	$arr_fail = array('item' => $item,'message' => $message);
	array_push($array, $arr_fail);
	return $array;
}
?>